import { Component } from "react";
import { connect } from 'dva';
import Link from 'umi/link';
import {
  Card,
  Button,
  Modal,
  Form,
  Input,
  Tabs,
  Spin,
  Select,
  Skeleton,
  DatePicker,
  Row,
  Col,
  Divider,
  TimePicker
} from 'antd';
import moment from 'moment';
import api from '@/api';
import MyIcon from '@/components/MyIcon';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ScrollSelect from '@/components/ScrollSelect';
import CusInputNumber from '@/components/CusInputNumber';
import styles from './Import.less';
import _ from 'lodash'
const { TabPane } = Tabs;
const FormItem = Form.Item;
const { Option } = Select;
@connect(({ loading }) => ({
  loading: loading.effects['productService/queryImportResult'],
  saveLoading: loading.effects['productService/saveImportResult'],
}))
@Form.create()
class ImportResult extends Component {
  state = {
    key: '1',
    visible: false,
    resultVisible: false,
    checkedRecord: {},
    counts: [0, 0],
    correctList: [],
    wrongList: []
  }
  week = [
    {
      key: 1,
      label: '1',
    },
    {
      key: 2,
      label: '2',
    },
    {
      key: 3,
      label: '3',
    },
    {
      key: 4,
      label: '4',
    },
    {
      key: 5,
      label: '5',
    },
    {
      key: 6,
      label: '6',
    },
    {
      key: 7,
      label: '7',
    },
  ];
  componentDidMount() {
    const { dispatch, location } = this.props;
    // 获取导入表格但解析结果
    dispatch({
      type: 'productService/queryImportResult',
      payload: {
        queryParams: {
          filePath: location.query.filePath
        }
      }
    }).then(({ errorCode, data }) => {
      if (errorCode === 0) {
        // 给表格内容增加下标,用来标记
        let fmtData = data.map((item, index) => Object.assign({}, item, { index }))
        this.setState({
          correctList: fmtData.filter(item => item.status === 1),
          wrongList: fmtData.filter(item => item.status === 0)
        })
      }
    })
  }

  formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 18 },
    },
  };

  columns = [
    {
      title: '始发地',
      dataIndex: 'startPlace',
      render: this.renderTableCell('startPlace')
    },
    {
      title: '目的地',
      dataIndex: 'endPlace',
      render: this.renderTableCell('endPlace')
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      render: this.renderTableCell('flightNo')
    },
    {
      title: '资源提供方名称',
      dataIndex: 'customerName',
      render: this.renderTableCell('customerId')
    },
  ]

  checkData(type, record) {
    if (1 === record.status) {
      return '';
    }
    if (record.errorMsg[type]) {
      return styles.errorData;
    }
    return '';
  }

  renderTableCell(type) {
    return (text, record) => (
      <span className={this.checkData(type, record)}>
        {text ? text : record.errorMsg[type]}
      </span>
    );
  }

  renderFooter = () => {
    const { key, correctList } = this.state;
    return (
      <div className={styles.listFooter}>
        <Button>
          <Link to={`/product/bind/import`}>取消</Link>
        </Button>
        {
          '1' === key && <Button
            type='primary'
            className={styles.footerMargin}
            disabled={!correctList.length}
            onClick={this.submitExcelData}
          >导入</Button>
        }
      </div>
    );
  };

  onRowHandle = (record) => {
    const { form: { setFields, resetFields } } = this.props;
    return {
      onClick: () => {
        resetFields()
        if (record.errorMsg) {
          let errorKeyList = Object.keys(record.errorMsg)
          let object = {}
          errorKeyList.forEach(item => {
            object[item] = { value: '', errors: [new Error(record.errorMsg[item])] }
          })

          setFields(object)
        }
        this.toggleModal(true, record)
      }
    }
  }

  renderTable(type) {
    const { loading } = this.props;
    const { correctList, wrongList, key } = this.state
    if (loading) return <></>
    let list = key === '1' ? _.cloneDeep(correctList) : _.cloneDeep(wrongList)
    return key === type && (

      <StandardTable
        rowKey="index"
        bordered
        className={'0' === key ? styles.canEditable : ''}
        loading={loading}
        pagination={false}
        data={{ list }}
        columns={this.columns}
        footer={this.renderFooter}
        onRow={'0' === key && this.onRowHandle}
      />
    )
  };

  submitExcelData = () => {
    const { dispatch, location } = this.props;
    const { correctList, wrongList } = this.state;
    dispatch({
      type: 'productService/saveImportResult',
      payload: {
        data: {
          dataList: correctList,
          productIdList: location.query.product.split(',')
        },
      }
    }).then(({ errorCode, data }) => {
      if (0 === errorCode) {
        this.setState({
          resultVisible: true,
          correctList: [],
          wrongList: [...wrongList, ...data],
          counts: [
            correctList.length,
            data.length
          ]
        })
      }
    })
  }

  onTabChange = key => {
    this.setState({ key });
  };

  toggleModal = (visible, checkedRecord = {}) => {
    this.setState({ visible, checkedRecord });
  }

  continueEdit = () => {
    this.setState({
      key: '0',
      resultVisible: false,
    });
  }

  spliceGenerate(checkedIndex, newItem, key) {
    return list => {
      const index = list.findIndex(item => item.index === checkedIndex);
      if ('1' === key) {
        if (-1 === index) {
          return list;
        }
        list.splice(index, 1, newItem);
      } else {
        if (-1 === index) {
          return [...list, newItem];
        }
        list.splice(index, 1);
      }
      return list;
    }
  }

  handleSubmit = () => {
    const {
      form: { validateFields }
    } = this.props;
    const { checkedRecord, key, correctList, wrongList } = this.state;
    validateFields((err, value) => {
      if (err) return;
      this.toggleModal(false);
      const newItem = {
        status: 1,
        errorMsg: {},
        startPlace: value.startPlace.key,
        endPlace: value.endPlace.key,
        flightNo: value.flightNo,
        customerId: value.customerId.key,
        customerName: value.customerId.label
      };

      this.setState({
        correctList: [...correctList, newItem],
        wrongList: wrongList.filter(item => item.index !== checkedRecord.index)
      })

    });
  }
  queryAirports = params => {
    return api.base.queryAirport({
      queryParams: params,
    });
  };
  querySuppliers = params => {
    return api.supplier.shortQuery({
      queryParams: params,
    });
  };
  render() {
    const {
      key,
      counts,
      visible,
      resultVisible,
      checkedRecord,
      correctList,
      wrongList
    } = this.state;
    const {
      form: { getFieldDecorator },
      saveLoading,
      loading
    } = this.props;
    return (
      <PageHeaderWrapper title="导入" backRoute={`/product/bind/import`}>
        <Card bordered={false} className={styles.importResult}>
          <Spin spinning={saveLoading === true} size="large">
            {loading && <Skeleton active />}
            {
              !loading &&
              <Tabs activeKey={key} onChange={this.onTabChange}>
                <TabPane tab={`正确(${correctList.length})`} key="1">
                  {this.renderTable('1')}
                </TabPane>
                <TabPane tab={`错误(${wrongList.length})`} key="0">
                  {this.renderTable('0')}
                </TabPane>
              </Tabs>
            }
          </Spin>
        </Card>
        <Modal
          width={800}
          title={'编辑'}
          visible={visible}
          maskClosable={false}
          onCancel={() => this.toggleModal(false)}
          onOk={this.handleSubmit}
        >
          <Row gutter={24}>
            <Col span={12}>
              <FormItem label="始&ensp;发&ensp;地" {...this.formItemLayout}>
                {getFieldDecorator('startPlace', {
                  rules: [
                    { required: true, message: '请选择始发地' },
                  ],
                  initialValue: {
                    key: checkedRecord.startPlace,
                    label: checkedRecord.startPlaceName,
                  },
                })(
                  <ScrollSelect
                    allowClear
                    optionLabel='shortName'
                    search={this.queryAirports}
                    optionKey="code"
                    style={{ width: '100%' }}
                  />
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label="目&ensp;的&ensp;地" {...this.formItemLayout}>
                {getFieldDecorator('endPlace', {
                  rules: [
                    { required: true, message: '请选择目的地' },
                  ],
                  initialValue: {
                    key: checkedRecord.endPlace,
                    label: checkedRecord.endPlaceName,
                  },
                })(
                  <ScrollSelect
                    allowClear
                    optionLabel='shortName'
                    search={this.queryAirports}
                    optionKey="code"
                    style={{ width: '100%' }}
                  />
                )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={12}>
              <FormItem label="航&emsp;&emsp;班" {...this.formItemLayout}>
                {getFieldDecorator('flightNo', {
                  rules: [
                    { required: true, message: '请输入航班' },
                    { pattern: /^[A-Z0-9]{5,7}$/i, message: '航班格式不正确' }
                  ],
                  initialValue: checkedRecord.flightNo,
                  normalize: (value, prevValue) => {
                    return value ? value.toUpperCase() : value;
                  },
                })(<Input maxLength={11} style={{ width: '100%' }} />)}
              </FormItem>
            </Col>
          </Row>
          <Divider orientation="left">其&emsp;&emsp;&emsp;他</Divider>
          <Row gutter={24}>
            <Col span={12}>
              <FormItem label="资源提供方" {...this.formItemLayout}>
                {getFieldDecorator('customerId', {
                  rules: [
                    {
                      required: true, message: '请选择资源提供方'
                    }
                  ],
                  initialValue: {
                    key: checkedRecord.customerId,
                    label: checkedRecord.customerName
                  },
                })(
                  <ScrollSelect
                    style={{ width: '100%' }}
                    showKey={false}
                    search={this.querySuppliers}
                    optionKey="id"
                    filterOption={false}
                    allowClear
                  />
                )}
              </FormItem>
            </Col>
          </Row>
        </Modal>
        <Modal
          title="导入:"
          width={360}
          keyboard={false}
          closable={false}
          maskClosable={false}
          visible={resultVisible}
          wrapClassName={styles.resultModal}
          footer={
            <>
              {
                wrongList.length
                  ? <Button style={{ marginRight: 40 }} onClick={this.continueEdit}>继续编辑</Button>
                  : null
              }
              <Button type='primary'>
                <Link to={`/product/bind`}>完成</Link>
              </Button>
            </>
          }
        >
          <div className={styles.resultTitle}>
            <MyIcon type='iconoss---tijiaochenggong'></MyIcon>
            <span>导入完成!</span>
          </div>
          <p>导入 {counts[0]} 个</p>
          <p>正确 {counts[0] - counts[1]} 个</p>
          <p>错误 {counts[1]} 个</p>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default ImportResult
